package com.company.linkedList;

import java.util.HashMap;

public class DetectCycle {


    public ListNode detectCycle(ListNode head) {
        return bySet(head);
    }


    private ListNode bySet(ListNode head){
        HashMap<ListNode,Integer> nodeRecord=new HashMap<>();

        ListNode node=head;
        int count=0;
        nodeRecord.put(head,count);
        node = node.next;
        count++;

        while (node!=null){
            if (nodeRecord.containsKey(node)) {
                break;
            }
            nodeRecord.put(node,count);
            node = node.next;
            count++;
        }
        return node;
    }
}
